"use strict";

/**
 * Config for the router
 */
angular
  .module("app")
  .run([
    "$rootScope",
    "$state",
    "$stateParams",
    "$modal",
    "$http",
    "toaster",
    "$timeout",
    "$location",
    "lodash",
    function(
      $rootScope,
      $state,
      $stateParams,
      $modal,
      $http,
      toaster,
      $timeout,
      $location,
      lodash
    ) {
      $rootScope.$state = $state;
      $rootScope.ws=null;
      $rootScope.$stateParams = $stateParams;
      $.loaderCount = 0;
      $rootScope.search = {};

      //根据类型获取sysconfig列表
      $rootScope.getSysConfigList = function(type) {
        var url = sys_config_url + "/select/get?type=" + type;
        var list = [];
        $.ajax({
          type: "get",
          url: url,
          contentType: "application/json; charset=utf-8",
          async: false,
          success: function(data) {
            if (data.code == 0) {
              list = data.data[type];
            }
          }
        });
        return list;
      };

      $rootScope.getStatusDesc = function(status) {
        var desc = status;
        if (status == "INT_NOT_START") {
          desc = "未开始";
        } else if (status == "INTEGRATIONING") {
          desc = "集成测试中";
        } else if (status == "HAND_OVER") {
          desc = "已交付运维";
        } else if (status == "ONLINE") {
          desc = "已上线";
        } else if (status == "PRO_NOT_CREATE") {
          desc = "未创建";
        } else if (status == "PRO_CREATED") {
          desc = "创建成功";
        } else if (status == "PRO_CREATE_ERROR") {
          desc = "创建失败";
        } else if (status == "PRO_DEVELOPING") {
          desc = "开发中";
        } else if (status == "PRO_TESTING") {
          desc = "测试中";
        } else if (status == "PRO_MERGED") {
          desc = "被合并";
        } else if (status == "TO_INTEGRATION") {
          desc = "交付集成";
        } else if (status == "BE_CANCEL") {
          desc = "被撤下";
        } else if (status == "PLAN_NEW") {
          desc = "新建项目";
        }else if (status == "CREATE") {
          desc = "创建";
        }else if (status == "PRD") {
          desc = "产品设计";
        }else if (status == "ISSUE_DEV") {
          desc = "立项开发";
        }else if (status == "ISSUE_ONLINE") {
          desc = "上线";
        }
        return desc;
      };

      function statusColor(value, type) {
        var co = "2AE02A";

        var config_value = type ? config_project_plan : config_need_status;
        angular.forEach(config_value, function(status) {
          if (value != "PLANS") {
            if (value == status.key) {
              co = status.color;
            }
          }
        });
        return co;
      }
      function isuueStatusColor(value) {
        var co = "2AE02A";
        var config_value=config_issue_status
        angular.forEach(config_value, function(status) {

            if (value == status.key) {
              co = status.color;
          }
        });
        return co;
      }

      function statusStr(value, type, isPlans) {
        var str = "";
        var config_value = type ? config_project_plan : config_need_status;
        angular.forEach(config_value, function(status) {
          if (value == status.key) {
            if (isPlans != value) {
              str = status.value;
            }
          }
        });
        return str;
      }
        function isuueStatusStr(value) {
            var str = "";
            var config_value=config_issue_status
            angular.forEach(config_value, function(status) {

                if (value == status.key) {
                    str = status.value;
                }
            });
            return str;
        }

      //各种进度条样式
      //根据数组下标进行判断进度条
      //[0]需求进展正常流程，[1]需求进展回退流程，[2]优先级，[3]周期时间，[4]多需求进展流程, [5]单个项目流程
        $rootScope.getsliderArray = [
          //需求的正常流程
          {
          options: {
            ceil: 5,
            readOnly: true,
            showSelectionBar: true,
            showTicksValues: true,
            stepsArray: [
              { value: "NO_ACCEPT" },
              { value: "DEPARTMENT_REVIEW" },
                {value:"ACCEPT"},
              { value: "CONFIRM" },
              { value: "PRODUCT_DESIGN" },
              // {value: "PLANS"},
              { value: "DEVING" },
              { value: "ONLINE" },
              { value: "CLOSED" }
            ],
            getSelectionBarColor: function(value) {
              return statusColor(value);
            },
            getPointerColor: function(value) {
              return statusColor(value);
            },
            translate: function(value, id, which) {
              return statusStr(value, "", "PLANS");
            }
          }
        },
        {
          options: {
            ceil: 3,
            readOnly: true,
            showSelectionBar: true,
            showTicksValues: true,
            stepsArray: [
              { value: "NO_ACCEPT" },
              { value: "ACCEPT" },
              { value: "FALLBACK" },
              { value: "CLOSED" }
            ],
            getSelectionBarColor: function(value) {
              return statusColor(value);
            },
            getPointerColor: function(value) {
              return statusColor(value);
            },
            translate: function(value, id, which) {
              return statusStr(value, "", "PLANS");
            }
          }
        },
        {
          options: {
            ceil: 4,
            showSelectionBar: true,
            vertical: true,
            getSelectionBarColor: function(value) {
              if (value >= 4) return "red";
              if (value >= 3) return "#ff00da";
              if (value >= 2) return "orange";
              if (value >= 1) return "yellow";
              return "#2AE02A";
            },
            getPointerColor: function(value) {
              if (value >= 4) return "red";
              if (value >= 3) return "#ff00da";
              if (value >= 2) return "orange";
              if (value >= 1) return "yellow";
              return "#2AE02A";
            },
            translate: function(value, id, which) {
              if (value >= 4) return "高";
              if (value >= 3) return "较高";
              if (value >= 2) return "中";
              if (value >= 1) return "较低";
              return "低";
            }
          }
        },
        {
          options: {
            floor: 0,
            ceil: 100,
            step: 1,
            minRange: 10,
            maxRange: 50
          }
        },
        {
          options: {
            ceil: 3,
            readOnly: true,
            showSelectionBar: true,
            showTicksValues: true,
            stepsArray: [
              { value: "NO_ACCEPT" },
              { value: "ACCEPT" },
              { value: "PLANS" },
              { value: "ONLINE" },
              { value: "CLOSED" }
            ],
            getSelectionBarColor: function(value) {
              return statusColor(value);
            },
            getPointerColor: function(value) {
              return statusColor(value);
            },
            translate: function(value, id, which) {
              return statusStr(value, "");
            }
          }
        },
        {
          options: {
            ceil: 3,
            readOnly: true,
            showSelectionBar: true,
            showTicksValues: true,
            stepsArray: [
              { value: "NEW" },
              { value: "PLAN_DEVELOPING" },
              { value: "INTEGRATIONING" },
              { value: "COMPLETED" }
            ],
            getSelectionBarColor: function(value) {
              return statusColor(value, "projectPlan");
            },
            getPointerColor: function(value) {
              return statusColor(value, "projectPlan");
            },
            translate: function(value, id, which) {
              return statusStr(value, "projectPlan", "PLANS");
            }
          }
        },
          {
              options: {
                  ceil: 5,
                  readOnly: true,
                  showSelectionBar: true,
                  showTicksValues: true,
                  stepsArray: [
                      { value: "INHAND" },
                      { value: "PRD" },
                      { value: "ISSUE_DEV" },
                      { value: "INTEGRATIONING" },
                      { value: "COMPLETE" },
                  ],
                  getSelectionBarColor: function(value) {
                      return isuueStatusColor(value);
                  },
                  getPointerColor: function(value) {
                      return isuueStatusColor(value);
                  },
                  translate: function(value) {
                      return isuueStatusStr(value);
                  }
              }
          },
      ];

      $rootScope.setUrlParams = function(url, urlArray) {
        var urlParam = "";
        angular.forEach(urlArray, function(params) {
          if (params.param) {
            urlParam += "&" + params.type + "=" + params.param;
          }
        });
        url = urlParam ? url + "?" + lodash.trimLeft(urlParam, "&") : url;
        return url;
      };

      $rootScope.showMessage = function(type, title, message) {
        toaster.pop(type, title, message);
        //$scope.$apply();
      };

      $rootScope.toasterSuccessInfo = function(message) {
        toaster.pop("success", "正确！", message);
      };

      $rootScope.toasterErrorInfo = function(message) {
        toaster.pop("error", "错误！", message);
      };

      $rootScope.toasterWarningInfo = function(message) {
        toaster.pop("warning", "警告！", message);
      };

      $rootScope.hidePreloader = function() {
        $.loaderCount--;
        if ($.loaderCount <= 0) {
          $(".mm-modal-loading").remove();
          $("body").removeClass("modal-open");
          $.loaderCount == 0;
        }
      };
      $rootScope.showPreloader = function(title) {
        $.loaderCount++;
        if ($("body").hasClass("modal-open")) {
          return;
        }
        $("body").append(
          '<div class="modal mm-modal-loading in" id="mmLoadingModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"><div class="mm-loading modal-dialog"><i class="fa fa-spinner fa-spin fa-4x fa-fw"></i>&nbsp;' +
            (title || "加载中...") +
            '</div></div><div class="modal-backdrop mm-modal-loading in" style="color: white; padding-top: 25%; padding-left: 50%;"><i class="fa fa-spinner fa-spin fa-4x fa-fw"></i></div>'
        );
        $("body").addClass("modal-open");
      };

      $rootScope.showPanelLoading = function() {
        $.loaderCount++;
        $(".mm-loading").css("display", "none");
        $(".mm-loading-icon").css("display", "block");
      };

      $rootScope.hidePanelLoading = function() {
        $.loaderCount--;
        if ($.loaderCount <= 0) {
          $(".mm-loading").css("display", "block");
          $(".mm-loading-icon").css("display", "none");
          $.loaderCount == 0;
        }
      };

      //返回历史
      $rootScope.backHistory = function() {
        var mb = myBrowser();
        // if ("Chrome" == mb) {
        //     var param = "";
        //     var toParams = getStorage("toParams");
        //     for (var i in toParams) {
        //         param += toParams[i];
        //     }
        // if (param.match(/[^\x00-\xff]/)) {
        //     console.log(window.history.back())
        // }
        // }
        window.history.back();
        return false;
      };

      //判断浏览器类型
      function myBrowser() {
        var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
        var isOpera = userAgent.indexOf("Opera") > -1;
        if (isOpera) {
          return "Opera";
        } //判断是否Opera浏览器
        if (userAgent.indexOf("Firefox") > -1) {
          return "FF";
        } //判断是否Firefox浏览器
        if (userAgent.indexOf("Chrome") > -1) {
          return "Chrome";
        }
        if (userAgent.indexOf("Safari") > -1) {
          return "Safari";
        } //判断是否Safari浏览器
        if (
          userAgent.indexOf("compatible") > -1 &&
          userAgent.indexOf("MSIE") > -1 &&
          !isOpera
        ) {
          return "IE";
        } //判断是否IE浏览器
      }

      $rootScope.gridDialog = function(gridEle, saveFun, closeFun) {
        var gridEle = gridEle;
        var modalInstance = $modal.open({
          animation: true,
          templateUrl: "gridDialogCtrl.html",
          controller: "gridDialogCtrl",
          keyboard: false,
          backdrop: "static",
          resolve: {
            gridEle: function() {
              return gridEle;
            }
          }
        });

        modalInstance.result.then(
          function(result) {
            if (closeFun) {
              closeFun();
            }
          },
          function(reason) {
            if (saveFun) {
              saveFun(reason);
            }
          }
        );
      };
      $rootScope.confirmWindow = function(htmlEle, saveFun, closeFun) {
        var htmlEle = htmlEle;
        var modalInstance = $modal.open({
          animation: true,
          templateUrl: "confirmCtrl.html",
          controller: "confirmCtrl",
          keyboard: false,
          backdrop: "static",
          resolve: {
            htmlEle: function() {
              return htmlEle;
            }
          }
        });

        modalInstance.result.then(
          function(result) {
            if (closeFun) {
              closeFun();
            }
          },
          function(reason) {
            if (saveFun) {
              saveFun(reason);
            }
          }
        );
      };
      //通用新增项目弹窗
      $rootScope.projectPlanSaveShow = function(
        reqDataList,
        statusList,
        saveFun,
        closeFun
      ) {
        var reqDataList = reqDataList;
        var statusList = statusList;
        var modalInstance = $modal.open({
          animation: true,
          templateUrl: "projectPlanSave.html",
          controller: "projectPlanSaveCtrl",
          keyboard: false,
          backdrop: "static",
          resolve: {
            reqDataList: function() {
              return reqDataList;
            },
            statusList: function() {
              return statusList;
            }
          }
        });

        modalInstance.result.then(
          function(result) {
            if (closeFun) {
              closeFun(result);
            }
          },
          function(reason) {
            if (saveFun) {
              saveFun(reason);
            }
          }
        );
      };
      //通用新建任务弹窗
      $rootScope.taskSaveShow = function(id, taskInfo, saveFun, closeFun) {
        var id = id;
        var modalInstance = $modal.open({
          animation: true,
          templateUrl: "AloneTaskSave.html",
          controller: "AloneTaskSaveCtrl",
          keyboard: false,
          backdrop: "static",
          resolve: {
            id: function() {
              return id;
            },
            taskInfo: function() {
              return taskInfo;
            }
          }
        });

        modalInstance.result.then(
          function(result) {
            if (closeFun) {
              closeFun();
            }
          },
          function(reason) {
            if (saveFun) {
              saveFun(reason);
            }
          }
        );
      };

      $rootScope.clean = function(app) {
        app.page = {};
        app.headerSave = {};
        app.brdSplit = {};
        app.headerPanel = {
          buttons: [], // tilte, func
          message: null,
          search: {
            show: false
          },
          searchBtn: "",
          issueShow: false
        };

        if ($rootScope.search.key != -1) {
          $timeout(function() {
            if (!app.headerPanel.search.show) {
              app.headerPanel.search.keyword = "";
            } else {
              app.headerPanel.search.keyword = $rootScope.search.value;
            }
            $rootScope.initializationSearch();
          }, 500);
        }
      };

      $rootScope.initHeaderElements = function(headerElemets) {
        headerElemets.searchEle = {
          show: false
        };
        headerElemets.sltTree = {
          show: false
        };
        headerElemets.selectEle = [];
        headerElemets.uiSltEle = [];
        if (headerElemets.btnEle) {
          headerElemets.btnEle.splice(0, headerElemets.btnEle.length);
        }
        if (headerElemets.switchs) {
          headerElemets.switchs.splice(0, headerElemets.switchs.length);
        }
      };

      $rootScope.initBreadcrumb = function(breadcrumb) {
        breadcrumb.splice(0, breadcrumb.length);
      };

      $rootScope.showIssueType = function(header) {
        console.log(header);
        header.showStatus = false;
      };

      $rootScope.popWindow = function(treeInfo, saveFun, closeFun) {
        var treeInfo = treeInfo;
        var modalInstance = $modal.open({
          animation: true,
          templateUrl: "confirmPop.html",
          controller: "confirmPopCtrl",
          keyboard: false,
          backdrop: "static",
          resolve: {
            treeInfo: function() {
              return treeInfo;
            }
          }
        });

        modalInstance.result.then(
          function(result) {
            if (closeFun) {
              closeFun();
            }
          },
          function(reason) {
            if (saveFun) {
              saveFun(reason);
            }
          }
        );
      };

      $rootScope.editTreeWindow = function(treeType, saveFun, closeFun) {
        console.log(treeType);
        var treeType = treeType;
        var modalInstance = $modal.open({
          animation: true,
          templateUrl: "confirmEditTree.html",
          controller: "confirmEditTreeCtrl",
          keyboard: false,
          backdrop: "static",
          resolve: {
            treeType: function() {
              return treeType;
            }
          }
        });

        modalInstance.result.then(
          function(result) {
            if (closeFun) {
              closeFun();
            }
          },
          function(reason) {
            if (saveFun) {
              saveFun(reason);
            }
          }
        );
      };
      $rootScope.getUserAccount = function() {
        return getUserAccount();
      };

      $rootScope.isMatrixRole = function() {
        // return $rootScope.isUserCanOperateByRole('pd', 'pdm');
        return true;
      };

      $rootScope.isMatrixCusRole = function(role) {
        return $rootScope.isUserCanOperateByRole(role);
      };

      $rootScope.addChildEle = function(saveFun, closeFun) {
        var modalInstance = $modal.open({
          animation: true,
          templateUrl: "addChildEle.html",
          controller: "addChildEleCtrl",
          keyboard: false,
          backdrop: "static"
          /*resolve: {
                         treeType : function(){
                         return treeType;
                         }
                         }*/
        });

        modalInstance.result.then(
          function(result) {
            if (closeFun) {
              closeFun();
            }
          },
          function(reason) {
            if (saveFun) {
              saveFun(reason);
            }
          }
        );
      };

      $rootScope.saveLayoutWindow = function(type, info, saveFun, closeFun) {
        var modalInstance = $modal.open({
          animation: true,
          templateUrl: "saveLayoutWindow.html",
          controller: "saveLayoutWindowCtrl",
          keyboard: false,
          backdrop: "static",
          resolve: {
            info: function() {
              return info;
            },
            type: function() {
              return type;
            }
          }
        });

        modalInstance.result.then(
          function(result) {
            if (closeFun) {
              closeFun();
            }
          },
          function(reason) {
            if (saveFun) {
              saveFun(reason);
            }
          }
        );
      };
      //websocket
      $rootScope.openWebSocket=function(ip,user,password,queue){
        if (location.search == '?ws') {
             $rootScope.ws = new WebSocket('ws://'+ip+':15674/ws');
        } else {
             $rootScope.ws = new SockJS('http://'+ip+':15674/stomp');
        }

        // 获得Stomp client对象
        var client = Stomp.over($rootScope.ws);

        // SockJS does not support heart-beat: disable heart-beats
        client.heartbeat.outgoing = 0;
        client.heartbeat.incoming = 0;

        // 定义连接成功回调函数
        ///queue/MATRIX_TEST_SEND.MATRIX.TEST.ALL.CNR 为队列名称，请根据场景自定义
        var on_connect = function(x) {
            //data.body是接收到的数据
            client.subscribe("/queue/"+queue, function(data) {
                var msg = data.body;
                alert("收到数据：" + msg);
            });
        };

        // 定义错误时回调函数
        var on_error = function() {
            console.log('error');
            return;
        };

        // 连接RabbitMQ
        client.connect(user, password, on_connect, on_error, '/');
        alert(">>>连接http://"+ip+":15674")

      }

      $rootScope.$on("$stateChangeStart", function(
        e,
        toState,
        toParams,
        fromState,
        fromParams
      ) {
        setStorage("toParams", toParams);
        window.onresize = "";
        if (toState.name == "access.signin") {
          return;
        }
        if($rootScope.ws!=null){
            $rootScope.ws.close();
        }
        var tokenId = getTokenId();
        if ("" == tokenId) {
          console.log("请登录!");
          setStorage("go_to_login_msg", "未找到登录信息,请重新登录!");
          e.preventDefault();
          $state.go("access.signin");
          return;
        }

        if (getUserAccount() != "") {
          //特殊的地址获取下用户偏好
          if (arrayContains(fondness_url, toState.name)) {
            $rootScope.getUserFondness();
          }
          return;
        }

        $http
          .get(beetle_auth_url + "/login/info?token_id=" + getTokenId(), {})
          .success(function(data) {
            if (data.success == false) {
              setStorage("go_to_login_msg", "获取用户信息失败,请重新登录!");
              e.preventDefault();
              $state.go("access.signin");
              return;
            }
            var rolelist_name = [];
            var rolelist_id = [];
            angular.forEach(data.data.role_list, function(list) {
              rolelist_name.push(list.role_name);
              rolelist_id.push(list.role_id);
            });
            setUserName(data.data.realname);
            setUserRole(rolelist_name);
            setUserId(data.data.id);
            setUserAccount(data.data.account);
            $rootScope.getUserFondness();
          });
      });

      $rootScope.getUserFondness = function() {
        $http
          .get(
            matrix_product_url +
              "/baseService/getSearchHistory?userAccount=" +
              getUserAccount()
          )
          .success(function(data) {
            if (data.code == "0") {
              saveFondness(data.data);
            }
          });
      };

      $rootScope.isUserCanOperateByRole = function() {
        var userRole = getUserRole();
        if (arrayContains(userRole, "admin")) {
          return true;
        }
        if (arrayContains(userRole, "matrix_admin")) {
          return true;
        }
        if (arguments.length == 0) {
          return false;
        }
        for (var i = 0; i < arguments.length; i++) {
          if (arrayContains(userRole, arguments[i])) {
            return true;
          }
        }
        return false;
      };

      $rootScope.userName = function() {
        return getUserName();
      };

      //sync=true 时 用的ajax，阻断页面请求，等待返回值
      $rootScope.winitAjaxGet = function(url, sync, successFunc, errorFunc) {
        if (url.indexOf("?") != -1) {
          url = url + "&tokenId=" + getTokenId();
        } else {
          url = url + "?tokenId=" + getTokenId();
        }

        if (sync && sync == "true") {
          //同步用ajax
          $.ajax({
            type: "get",
            url: url,
            async: false,
            success: function(data) {
              if (successFunc) {
                successFunc(data);
              }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
              dealStatus(XMLHttpRequest.status, errorFunc);
            }
          });
        } else {
          //异步用http
          $http
            .get(url)
            .success(function(data) {
              if (successFunc) {
                successFunc(data);
              }
            })
            .error(function(data, status, headers, config) {
              dealStatus(status, errorFunc);
            });
        }
      };
      $rootScope.winitAjaxPost = function(
        url,
        sync,
        data,
        successFunc,
        errorFunc
      ) {
        if (!data) {
          data = new Object();
        }
        data.tokenId = getTokenId();
        if (sync && sync == "true") {
          //同步用ajax
          $.ajax({
            type: "post",
            url: url,
            data: data,
            async: false,
            success: function(d) {
              if (successFunc) {
                successFunc(d);
              }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
              dealStatus(XMLHttpRequest.status, errorFunc);
            }
          });
        } else {
          //异步用http
          $http
            .post(url, data)
            .success(function(d) {
              if (successFunc) {
                successFunc(d);
              }
            })
            .error(function(data, status, headers, config) {
              dealStatus(status, errorFunc);
            });
        }
      };

      //处理http请求返回的错误状态码
      //403 时，退出登录，跳转到登录页面
      function dealStatus(status, errorFunc) {
        if (status == "403") {
          $http
            .get(beetle_auth_url + "/login/login_out?token_id=" + getTokenId())
            .success(function(data) {
              storage.clear();
              $state.go("access.signin");
            });
        } else {
          if (errorFunc) {
            errorFunc();
          }
        }
      }
    }
  ])
  .config([
    "$stateProvider",
    "$urlRouterProvider",
    "JQ_CONFIG",
    "MODULE_CONFIG",
    function($stateProvider, $urlRouterProvider, JQ_CONFIG, MODULE_CONFIG) {
      var layout = "tpl/app.html";
      $urlRouterProvider.otherwise("/access/signin");

      $stateProvider
        //martix
        .state("app.matrix", {
          url: "/matrix",
          template: '<div ui-view class="fade-in"></div>'
        })

        //用户故事
        .state("app.issue", {
          url: "/issue",
          template: '<div ui-view class="fade-in"></div>'
        })
        .state("app.issue.list", {
          url: "/list",
          templateUrl: getTemplateUrl("matrix/issue/tpl/issue.html"),
          resolve: load([
            "mwl.confirm",
            "ui.select",
            "data-table",
            "angularBootstrapNavTree",
            "matrix/issue/controller/issue.js",
            "js/controllers/tree.js"
          ]),
          controller: "pondCtrl"
        })
        //系统配置
        .state("app.config", {
          url: "/config",
          template: '<div ui-view class="fade-in"></div>'
        })
        .state("app.config.info", {
          url: "/info/:type",
          templateUrl: getTemplateUrl("matrix/sysConfig/tpl/sysConfig.html"),
          controller: "sysConfigCtrl",
          resolve: load([
            "xeditable",
            "ui.select",
            "data-table",
            "matrix/sysConfig/controller/sysConfig.js"
          ])
        })
        .state("app.config.wsAgent", {
          url: "/wsAgent",
          templateUrl: getTemplateUrl("matrix/sysConfig/tpl/wsAgent.html"),
          controller: "wsAgentCtrl",
          resolve: load([
            "xeditable",
            "angularBootstrapNavTree",
            "matrix/sysConfig/controller/wsAgent.js",
            "js/controllers/tree.js"
          ])
        })
        .state("app.config.tree", {
          url: "/tree",
          templateUrl: getTemplateUrl("matrix/sysConfig/tpl/tree.html"),
          controller: "treeCtrl",
          resolve: load([
            "ui.select",
            "data-table",
            "xeditable",
            "angularBootstrapNavTree",
            "matrix/sysConfig/controller/tree.js",
            "js/controllers/tree.js"
          ])
        })
        .state("app.config.feature", {
          url: "/feature",
          templateUrl: getTemplateUrl("matrix/sysConfig/tpl/feature.html"),
          resolve: load([
            "mwl.confirm",
            "angularBootstrapNavTree",
            "xeditable",
            "ui.select",
            "data-table",
            "matrix/sysConfig/controller/feature.js",
            "js/controllers/tree.js"
          ]),
          controller: "deleteFeatureCtrl"
        })
        //需求
        .state("app.need", {
          url: "/need",
          template: '<div ui-view class="fade-in"></div>'
        })
        .state("app.need.list", {
          url: "/list/:accept/:appointAccept",
          templateUrl: getTemplateUrl("matrix/need/tpl/management.html"),
          resolve: load([
            "ngDropover",
            "ng-cooltip",
            "ui.select",
            "data-table",
            "mwl.confirm",
            "angularBootstrapNavTree",
            "matrix/need/controller/management.js",
            "js/controllers/tree.js"
          ]),
          controller: "managementCtrl"
        })
        .state("app.need.count", {
          url: "/count",
          templateUrl: getTemplateUrl("matrix/need/tpl/count.html"),
          resolve: load([
            "ui.select",
            "data-table",
            "mwl.confirm",
            "angularBootstrapNavTree",
            "matrix/need/controller/count.js",
            "js/controllers/tree.js"
          ]),
          controller: "countCtrl"
        })
        .state("app.need.acceptList", {
          url: "/acceptList/:accept/:appointAccept",
          templateUrl: getTemplateUrl("matrix/need/tpl/acceptList.html"),
          resolve: load([
            "ui.select",
            "data-table",
            "mwl.confirm",
            "angularBootstrapNavTree",
            "matrix/need/controller/acceptList.js",
            "js/controllers/tree.js"
          ]),
          controller: "acceptListCtrl"
        })
        .state("app.need.add", {
          url: "/addNeed/:type/:id/:accept/:appointAccept",
          templateUrl: getTemplateUrl("matrix/need/tpl/add.html"),
          resolve: load([
            "ui.select",
            "angularBootstrapNavTree",
            "data-table",
            "matrix/need/controller/add.js",
            "js/controllers/tree.js"
          ]),
          controller: "addNeedCtrl"
        })
        //martix requirement
        .state("app.req", {
          url: "/req",
          template: "<div ui-view></div>"
        })
        .state("app.req.list", {
          url: "/list",
          templateUrl: getTemplateUrl(
            "matrix/requirement/tpl/requirementList.html"
          ),
          resolve: load([
            "mwl.confirm",
            "ui.select",
            "data-table",
            "angularBootstrapNavTree",
            "matrix/requirement/controller/requirementList.js",
            "js/controllers/tree.js"
          ]),
          controller: "requirementCtrl"
        })
        .state("app.req.summary", {
          url: "/summary/:reqId",
          templateUrl: getTemplateUrl("matrix/requirement/tpl/summary.html"),
          resolve: load([
            "ui.select",
            "data-table",
            "xeditable",
            "angularBootstrapNavTree",
            "matrix/requirement/controller/summary.js",
            "js/controllers/tree.js"
          ]),
          controller: "summaryCtrl"
        })
        .state("app.req.mindMap", {
          url: "/mindMap/:reqId",
          templateUrl: getTemplateUrl("matrix/requirement/tpl/mindMap.html"),
          resolve: load([
            "ui.select",
            "data-table",
            "xeditable",
            "angularBootstrapNavTree",
            "matrix/requirement/controller/mindMap.js",
            "js/controllers/tree.js"
          ]),
          controller: "mindMapCtrl"
        })
        .state("app.req.demand", {
          url: "/demand/:reqId",
          templateUrl: getTemplateUrl("matrix/requirement/tpl/demand.html"),
          resolve: load([
            "mwl.confirm",
            "ui.select",
            "data-table",
            "xeditable",
            "angularBootstrapNavTree",
            "matrix/requirement/controller/demand.js",
            "js/controllers/tree.js"
          ]),
          controller: "demandCtrl"
        })
        .state("app.req.flow", {
          url: "/flow/:reqId",
          templateUrl: getTemplateUrl("matrix/requirement/tpl/flow.html"),
          resolve: load([
            "mwl.confirm",
            "ui.select",
            "data-table",
            "xeditable",
            "angularBootstrapNavTree",
            "matrix/requirement/controller/flow.js",
            "js/controllers/tree.js"
          ]),
          controller: "flowCtrl"
        })
        .state("app.req.feature", {
          url: "/feature/:reqId",
          templateUrl: getTemplateUrl("matrix/requirement/tpl/feature.html"),
          resolve: load([
            "ui.select",
            "data-table",
            "xeditable",
            "angularBootstrapNavTree",
            "matrix/requirement/controller/feature.js",
            "js/controllers/tree.js"
          ]),
          controller: "featureCtrl"
        })
        .state("app.req.userManualGuide", {
          url: "/userManualGuide/:reqId",
          templateUrl: getTemplateUrl(
            "matrix/requirement/tpl/userManualGuide.html"
          ),
          resolve: load([
            "ui.select",
            "data-table",
            "xeditable",
            "angularBootstrapNavTree",
            "matrix/requirement/controller/userManualGuide.js",
            "js/controllers/tree.js"
          ]),
          controller: "userManualGuideCtrl"
        })
        .state("app.req.reportForm", {
          url: "/reportForm/:reqId",
          templateUrl: getTemplateUrl("matrix/requirement/tpl/reportForm.html"),
          resolve: load([
            "ui.select",
            "data-table",
            "xeditable",
            "angularBootstrapNavTree",
            "matrix/requirement/controller/reportForm.js",
            "js/controllers/tree.js"
          ]),
          controller: "reportFormCtrl"
        })
        .state("app.req.remarks", {
          url: "/remarks/:reqId",
          templateUrl: getTemplateUrl("matrix/requirement/tpl/remarks.html"),
          resolve: load([
            "mwl.confirm",
            "ui.select",
            "data-table",
            "xeditable",
            "angularBootstrapNavTree",
            "matrix/requirement/controller/remarks.js",
            "js/controllers/tree.js"
          ]),
          controller: "remarksCtrl"
        })
        .state("app.req.demo", {
          url: "/demo/:reqId",
          templateUrl: getTemplateUrl("matrix/requirement/tpl/demo.html"),
          resolve: load([
            "ui.select",
            "data-table",
            "xeditable",
            "infinite-scroll",
            "angularBootstrapNavTree",
            "matrix/requirement/controller/demo.js",
            "js/controllers/tree.js"
          ]),
          controller: "demoCtrl"
        })
        .state("app.req.debunker", {
          url: "/debunker/:reqId",
          templateUrl: getTemplateUrl("matrix/requirement/tpl/debunker.html"),
          resolve: load([
            "ui.select",
            "data-table",
            "xeditable",
            "angularBootstrapNavTree",
            "matrix/requirement/controller/debunker.js",
            "js/controllers/tree.js"
          ]),
          controller: "debunkerCtrl"
        })
        .state("app.req.notice", {
          url: "/notice/:reqId",
          templateUrl: getTemplateUrl("matrix/requirement/tpl/notice.html"),
          resolve: load([
            "ui.select",
            "data-table",
            "xeditable",
            "angularBootstrapNavTree",
            "matrix/requirement/controller/notice.js",
            "js/controllers/tree.js"
          ]),
          controller: "reqNoticeCtrl"
        })
        .state("app.req.layout", {
          url: "/layout/:reqId",
          templateUrl: getTemplateUrl("matrix/requirement/tpl/layout.html"),
          resolve: load([
            "mwl.confirm",
            "angularBootstrapNavTree",
            "xeditable",
            "ui.select",
            "data-table",
            "matrix/requirement/controller/layout.js",
            "js/controllers/tree.js"
          ]),
          controller: "layoutCtrl"
        })
        .state("app.req.details", {
          url: "/details/:reqId/:featureId/:sys/:type",
          templateUrl: getTemplateUrl("matrix/requirement/tpl/featureDetails.html"),
          resolve: load([
            "mwl.confirm",
            "angularBootstrapNavTree",
            "xeditable",
            "ui.select",
            "data-table",
            "matrix/requirement/controller/featureDetails.js",
            "js/controllers/tree.js"
          ]),
          controller: "detailsCtrl"
        })
        //martix projectPlan
        .state("app.plan", {
          url: "/plan",
          template: '<div ui-view class="fade-in"></div>'
        })
        .state("app.plan.list", {
          url: "/list",
          templateUrl: getTemplateUrl(
            "matrix/projectPlan/tpl/projectPlanList.html"
          ),
          resolve: load([
            "ui.select",
            "data-table",
            "angularBootstrapNavTree",
            "matrix/projectPlan/controller/projectPlanList.js",
            "js/controllers/tree.js"
          ]),
          controller: "projectPlanCtrl"
        })
        .state("app.plan.summary", {
          url: "/summary/:type/:id",
          templateUrl: getTemplateUrl("matrix/projectPlan/tpl/summary.html"),
          resolve: load([
            "ui.select",
            "data-table",
            "matrix/projectPlan/controller/summary.js"
          ]),
          controller: "summaryCtrl"
        })
        .state("app.plan.demand", {
          url: "/demand/:type/:id",
          templateUrl: getTemplateUrl("matrix/projectPlan/tpl/demand.html"),
          resolve: load([
            "ui.select",
            "data-table",
            "ngMaterial",
            "diff-match-patch",
            "xeditable",
            "infinite-scroll",
            "angularBootstrapNavTree",
            "matrix/projectPlan/controller/demand.js",
            "js/controllers/tree.js"
          ]),
          controller: "demandCtrl"
        })
        .state("app.plan.planTask", {
          url: "/planTask/:type/:id",
          templateUrl: getTemplateUrl("matrix/projectPlan/tpl/planTask.html"),
          resolve: load([
            "ui.select",
            "data-table",
            "matrix/projectPlan/controller/planTask.js"
          ]),
          controller: "planTaskCtrl"
        })
        .state("app.plan.project", {
          url: "/project/:type/:id",
          templateUrl: getTemplateUrl("matrix/projectPlan/tpl/project.html"),
          resolve: load([
            "ui.select",
            "data-table",
            "ngAnimate",
            "ngTouch",
            "ui.bootstrap",
            "matrix/projectPlan/controller/project.js",
            "matrix/component/controller/createProjectModel.js",
            "matrix/component/controller/switchBranchModal.js",
            "matrix/component/controller/editionModel.js"
          ]),
          controller: "projectCtrl"
        })
        .state("app.plan.env", {
          url: "/env/:type/:id",
          templateUrl: getTemplateUrl("matrix/projectPlan/tpl/env.html"),
          resolve: load([
            "ui.select",
            "data-table",
            "matrix/projectPlan/controller/env.js"
          ]),
          controller: "envCtrl"
        })
        //martix prototype
        // 原型功能未完善，暂时不提供功能
        .state("app.prototype", {
          url: "/prototype",
          template: '<div ui-view class="fade-in"></div>'
        })
        .state("app.prototype.edit", {
          url: "/edit/:reqId/:reqName",
          templateUrl: getTemplateUrl("matrix/prototype/tpl/edit.html"),
          resolve: load([
            "angularBootstrapNavTree",
            "xeditable",
            "matrix/prototype/controller/edit.js",
            "js/controllers/tree.js"
          ]),
          controller: "prototypeEditCtrl"
        })
        //知识库
        .state("app.repository", {
          url: "/repository",
          template: '<div ui-view class="fade-in"></div>'
        })
        .state("app.repository.flow", {
          url: "/flow/:reqId",
          templateUrl: getTemplateUrl("matrix/repository/tpl/flowMap.html"),
          resolve: load([
            "mwl.confirm",
            "angularBootstrapNavTree",
            "xeditable",
            "ui.select",
            "data-table",
            "matrix/repository/controller/flowMap.js",
            "js/controllers/tree.js"
          ]),
          controller: "flowMapCtrl"
        })
        .state("app.repository.featureMap", {
          url: "/featureMap/:reqId",
          templateUrl: getTemplateUrl("matrix/repository/tpl/featureMap.html"),
          resolve: load([
            "mwl.confirm",
            "angularBootstrapNavTree",
            "xeditable",
            "ui.select",
            "data-table",
            "matrix/repository/controller/featureMap.js",
            "js/controllers/tree.js"
          ]),
          controller: "featureMapCtrl"
        })
        // ucloud2.0
        .state("app.ucloud2", {
          url: "/ucloud2",
          template: "<div ui-view class='fade-in'></div>"
        })
        .state("app.ucloud2.area", {
          url: "/area",
          templateUrl: getTemplateUrl("matrix/ucloud2.0/tpl/area.html"),
          resolve: load(["ui.select", "data-table", "matrix/ucloud2.0/controller/area.js", "js/controllers/tree.js"]),
          controller: "areaCtrl"
        })
        .state("app.ucloud2.config", {
          url: "/config",
          templateUrl: getTemplateUrl("matrix/ucloud2.0/tpl/config.html"),
          resolve: load(["ui.select", "data-table", "matrix/ucloud2.0/controller/config.js", "js/controllers/tree.js"]),
          controller: "configCtrl"
        })
        .state("app.ucloud2.node", {
          url: "/node",
          templateUrl: getTemplateUrl("matrix/ucloud2.0/tpl/node.html"),
          resolve: load(["ui.select", "data-table", "matrix/ucloud2.0/controller/node.js", "js/controllers/tree.js"]),
          controller: "nodeCtrl"
        })
        .state("app.ucloud2.publish", {
          url: "/publish",
          templateUrl: getTemplateUrl("matrix/ucloud2.0/tpl/publish.html"),
          resolve: load(["ui.select", "data-table", "matrix/ucloud2.0/controller/publish.js", "js/controllers/tree.js"]),
          controller: "publishCtrl"
        })
        //组件
        .state("app.component", {
          url: "/component",
          template: '<div ui-view class="fade-in"></div>'
        })
        .state("app.component.demo", {
          url: "/demo",
          templateUrl: getTemplateUrl("matrix/componentDemo/demo.html"),
          resolve: load([
            "angularBootstrapNavTree",
            "xeditable",
            "ui.select",
            "data-table",
            "matrix/componentDemo/demo.js",
            "js/controllers/tree.js"
          ])
        })
        .state("app.component.flow_2", {
          url: "/flow_2",
          templateUrl: getTemplateUrl("matrix/componentDemo/familyTree.html"),
          resolve: load([
            "angularBootstrapNavTree",
            "xeditable",
            "ui.select",
            "data-table",
            "matrix/componentDemo/familyTree.js",
            "js/controllers/tree.js"
          ])
        })
        .state("app.component.datatable", {
          url: "/datatable/:reqId",
          templateUrl: getTemplateUrl("matrix/componentDemo/datatable.html"),
          resolve: load([
            "mwl.confirm",
            "ui.select",
            "data-table",
            "xeditable",
            "angularBootstrapNavTree",
            "matrix/componentDemo/datatable.js",
            "js/controllers/tree.js"
          ]),
          controller: "datatableCtrl"
        })
        .state("app.component.chart", {
          url: "/chart",
          templateUrl: getTemplateUrl("matrix/componentDemo/chart.html"),
          resolve: load([
            "angularBootstrapNavTree",
            "data-table",
            "matrix/componentDemo/chart.js",
            "js/controllers/tree.js"
          ]),
          controller: "chartCtrl"
        })
        .state("app.component.expression", {
          url: "/expression",
          templateUrl: getTemplateUrl("matrix/componentDemo/expression.html"),
          resolve: load([
            "angularBootstrapNavTree",
            "data-table",
            "matrix/componentDemo/expression.js",
            "js/controllers/tree.js"
          ]),
          controller: "expressionCtrl"
        })
        .state("app.component.jsonedit", {
          url: "/jsonedit",
          templateUrl: getTemplateUrl("matrix/componentDemo/jsonedit.html"),
          resolve: load([
            "ui.sortable",
            "JSONedit",
            "matrix/componentDemo/jsonedit.js",
            "js/controllers/tree.js"
          ]),
          controller: "jsoneditCtrl"
        })
        .state("app.component.gantt", {
          url: "/gantt",
          templateUrl: getTemplateUrl("matrix/componentDemo/gantt.html"),
          resolve: load(["matrix/componentDemo/gantt.js"]),
          controller: "ganttCtrl"
        })
        //user
        .state("app.password", {
          url: "/password",
          templateUrl: getTemplateUrl("matrix/user/tpl/user.html"),
          resolve: load(["matrix/user/controller/userController.js"]),
          controller: "userCtrl"
        })
        .state("app", {
          abstract: true,
          url: "/app",
          templateUrl: getTemplateUrl(layout)
        })
        .state("app.dashboard-v1", {
          url: "/dashboard-v1",
          templateUrl: getTemplateUrl("matrix/matrix-main.html"),
          resolve: load(["matrix/matrix-main.js"])
        })
        .state("access", {
          url: "/access",
          template: '<div ui-view class="fade-in-right-big smooth"></div>'
        })
        .state("access.signin", {
          url: "/signin",
          templateUrl: getTemplateUrl("matrix/login/tpl/login.html"),
          resolve: load(["matrix/login/controller/login.js"])
        })
        .state("app.component.gate", {
          url: "/gate/:serviceId/:methodName",
          templateUrl: getTemplateUrl(
            "matrix/servicegate/tpl/servicegate.html"
          ),
          resolve: load([
            "matrix/servicegate/controller/servicegate.js",
            "ui.select",
            "diff-match-patch",
            "JSONedit"
          ]),
          controller: "gateCtr"
        })
        .state("app.component.openapi", {
          url: "/openpai/:hasAdmin/:actionName",
          templateUrl: getTemplateUrl("matrix/openapi/tlp/openapi.html"),
          resolve: load([
            "matrix/openapi/controller/openapi.js",
            "ui.select",
            "diff-match-patch",
            "JSONedit"
          ]),
          controller: "openapiCtr"
        })
        .state("app.component.paramdiffs", {
          url: "/paramdiffs",
          templateUrl: getTemplateUrl("matrix/componentDemo/diffdemo.html"),
          resolve: load([
            "matrix/componentDemo/diffdemo.js",
            "ui.select",
            "diff-match-patch",
            "JSONedit"
          ]),
          controller: "paramdiffsCtrl"
        })
        .state("app.component.uschedule", {
          url: "/uschedule/:taskName",
          templateUrl: getTemplateUrl("matrix/uschedule/tlp/uschedule.html"),
          resolve: load([
            "matrix/uschedule/controller/uschedule.js",
            "ui.select",
            "data-table"
          ]),
          controller: "uscheduleCtr"
        })
        .state("app.component.ucloud", {
          url: "/ucloud/",
          templateUrl: getTemplateUrl("matrix/ucloud/tlp/ucloud.html"),
          resolve: load([
            "matrix/ucloud/controller/ucloud.js",
            "ui.select",
            "JSONedit",
            "data-table"
          ]),
          controller: "ucloudCtr"
        });

      function load(srcs, callback) {
        return {
          deps: [
            "$ocLazyLoad",
            "$q",
            function($ocLazyLoad, $q) {
              var deferred = $q.defer();
              var promise = false;
              srcs = angular.isArray(srcs) ? srcs : srcs.split(/\s+/);
              if (!promise) {
                promise = deferred.promise;
              }
              angular.forEach(srcs, function(src) {
                promise = promise.then(function() {
                  if (JQ_CONFIG[src]) {
                    // return $ocLazyLoad.load(JQ_CONFIG[src]);
                    return $ocLazyLoad.load(JQ_CONFIG[src], {
                      cache: false
                    });
                  }
                  angular.forEach(MODULE_CONFIG, function(module) {
                    if (module.name == src) {
                      name = module.name;
                    } else {
                      name = src;
                    }
                  });
                  // return $ocLazyLoad.load(name);
                  return $ocLazyLoad.load(name, {
                    cache: false
                  });
                });
              });
              deferred.resolve();
              return callback
                ? promise.then(function() {
                    return callback();
                  })
                : promise;
            }
          ]
        };
      }
    }
  ]);
